﻿
/* 
 * Since 2008 - 2012
 */
package com.hh.bss.customer.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;


import com.hh.bss.base.*;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.customer.dao.*;
import com.hh.bss.customer.entity.*;
import com.hh.bss.customer.service.*;
import com.hh.bss.customer.vo.query.*;
import com.hh.bss.project.service.SearchProjectCvService;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.entity.CvContactDetail;
import com.hh.bss.talent.entity.CvSalary;
import com.hh.bss.talent.service.CvService;
import com.hh.bss.util.*;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.ListRange;

import java.util.*;





@Controller
public class CompanyCvController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	private static final ObjectMapper objectMapper = new ObjectMapper();
	private CompanyCvService companyCvService;
	private SearchProjectCvService searchProjectCvService;
	@Autowired   //
	private CustomerContacterService customerContacterService;
	private CompanyCv companyCv;
	java.lang.Integer id = null;
	private String[] items;

	private CvService cvService;
	public void setCvServiceImpl(CvService service) {
		this.cvService = service;
	}
	
	
	/** 通过spring自动注入 */
	public void setCompanyCvServiceImpl(CompanyCvService service) {
		this.companyCvService = service;
	}	
	public void setSearchProjectCvServiceImpl(SearchProjectCvService service) {
		this.searchProjectCvService = service;
	}

	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}



	/**
	 * ExtGrid使用
	 * 列表
	 * @throws IOException
	 */
	public void list(HttpServletRequest request,HttpServletResponse response,CompanyCvQuery companyCvQuery) throws IOException
	{
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyCvService.findPage(companyCvQuery);
		
		List<CompanyCv> CompanyCvlist = (List) page.getResult();
		ListRange<CompanyCv> resultList = new ListRange<CompanyCv>();
		resultList.setRows(CompanyCvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response,resultList);
	}
	public void listcvcompany(HttpServletRequest request,HttpServletResponse response,CompanyCvQuery companyCvQuery) throws IOException
	{
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		String cvId = request.getParameter("cvId");
		if(cvId !=null && !"".equals(cvId)){
			companyCvQuery.setCvId(Integer.valueOf(cvId));
			List<CompanyCvQuery> CompanyCvlist = companyCvService.findCvCompany(companyCvQuery);
			ListRange<CompanyCvQuery> resultList = new ListRange<CompanyCvQuery>();
			resultList.setRows(CompanyCvlist);
			resultList.setMessage("ok");
			resultList.setSuccess(true);
			outJson(response,resultList);
		}
		
	}

	public void listprojectcompanycv(HttpServletRequest request,HttpServletResponse response,CompanyCvQuery companyCvQuery) throws IOException
	{
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyCvService.findSearchProjectCompanyCvPage(companyCvQuery);
		
		List<CompanyCv> CompanyCvlist = (List) page.getResult();
		ListRange<CompanyCv> resultList = new ListRange<CompanyCv>();
		resultList.setRows(CompanyCvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response,resultList);
	}
	public void listcompanycv(HttpServletRequest request,HttpServletResponse response,CompanyCvQuery companyCvQuery) throws IOException
	{
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = companyCvService.findCompanyCv(companyCvQuery);
		
		List<CompanyCv> CompanyCvlist = (List) page.getResult();
		ListRange<CompanyCv> resultList = new ListRange<CompanyCv>();
		resultList.setRows(CompanyCvlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response,resultList);
	}
	/**
	 * extGrid保存
	 * @throws IOException
	 */
	public void save(HttpServletRequest request,HttpServletResponse response,CompanyCv companyCv) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
                        //设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null&&com.hh.bss.util.BeanUtils.isExistsProperty(CompanyCv.class,"creator")) {
						try{com.hh.bss.util.BeanUtils.setProperty(companyCv,"creator",onlineUser.getUsername());}catch(Exception ex){}
					}
				}
							
			if (com.hh.bss.util.BeanUtils.isExistsProperty(CompanyCv.class,"createDt")) {
					try{com.hh.bss.util.BeanUtils.setProperty(companyCv,"createDt",new Date());}catch(Exception ex){}
				}
			
			
			companyCvService.save(companyCv);
			result.put("success", true);
			result.put("msg", "添加成功!");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	
	/**
	 * extGrid修改
	 * @throws IOException
	 */
	public void update(HttpServletRequest request,HttpServletResponse response,CompanyCv companyCv) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
                        CompanyCv oldcompanyCv = (CompanyCv)companyCvService.getById(companyCv.getId());
                         
			bind(request,oldcompanyCv);
                        //设置修改用户和修改时间 
                        com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null&&com.hh.bss.util.BeanUtils.isExistsProperty(CompanyCv.class,"modifier")) {
						try{com.hh.bss.util.BeanUtils.setProperty(oldcompanyCv,"modifier",onlineUser.getUsername());}catch(Exception ex){}
					}
				}
							
			if (com.hh.bss.util.BeanUtils.isExistsProperty(CompanyCv.class,"modifiedDt")) {
					try{com.hh.bss.util.BeanUtils.setProperty(oldcompanyCv,"modifiedDt",new Date());}catch(Exception ex){}
				}


			companyCvService.update(oldcompanyCv);
			result.put("success", true);
			result.put("msg", "修改成功!");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	public void savecompanycv(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		
		Cv cv=new Cv();
		
		
		CvSalary cvSalary=new CvSalary();
		CompanyCv companyCv=new CompanyCv(); 
		String contact_json =request.getParameter("contact_data").toString(); //联系信息
		List<CvContactDetail> contact_list = objectMapper.readValue( contact_json, new TypeReference<List<CvContactDetail>>(){});
		//List contacts=new ArrayList();
		try
		{
			
			//String cvId=request.getParameter("cvId");
			String companyId=request.getParameter("companyId");
			
			
			bind(request,cv);
			bind(request,cvSalary);
			bind(request,companyCv);
			
			if (!StringHelper.isEmpty(companyId)) companyCv.setCompanyId(StringHelper.parseInteger(companyId, 0));
			//判断人选是否增加过
			
			if (companyCv.getCompanyId()==null) companyCv.setCompanyId(0);
			if (companyCv.getDeptId()==null) companyCv.setDeptId(0);
			if (companyCv.getTitleId()==null) companyCv.setTitleId(0);
			 //设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null) {
						
						cv.setNameInformer(onlineUser.getUsername());
						cv.setNameDt(new Date());
						//cv.setResumeInformer(onlineUser.getUsername());
						//cv.setResumeDt(new Date());
						if (StringHelper.isEmpty(cv.getNameInformer())) {
							cv.setNameInformer(cv.getCreator());
						}
						cv.setCreator(onlineUser.getUsername());
						cv.setCreateDt(new Date());
						
						if (cv.getNameDt()==null) {
							cv.setNameDt(cv.getCreateDt());
						}
						if (cv.getResumeDt()==null) {
							cv.setNameDt(cv.getCreateDt());
						}

						cv.setCvFrom(ConstantDic.CvFrom_H);						
					}
				}
		  
		    
			if(!cvService.checkUser(cv,contact_list)){}else{
				result.put("failure", true);
				result.put("msg", "人才重复,请检查 姓名 邮件  是否存在相同的记录.");
				outJson(response,result);				
				return;
				
			}
	    	
			companyCvService.saveCompanyCvInfo(cv,companyCv,cvSalary,contact_list);
    		result.put("success", true);
    		result.put("msg", "添加成功!");
    		
    		////如果选择了现任公司  和 人选类型  则在客户联系人中出现
    		//选择的人选类型 如果是客户联系人  把它添加到客户联系人中  并检查客户联系人是否存在
    		//i//f(cv.getCompanyId() != null && ""cv.getCvType())
    		if(companyId !=null && cv.getCvType() != null){
				//根据公司Id 找到客户公司Id
				Integer custId  = customerContacterService.getCustIdByCompanyId(new Integer(companyId));
				if(custId != null){
					//cv.cv_type从常量选择，人才类型：2020:BD联系人，2021:合作决策人，2022:职位联系人，
					//2023:收款联系人，2024:成功候选人（录入offer后更新），2025 ：普通候选人 
					//对应客户联系人 //CT-BD联系人  CP-合作决策人 JC-职位联系人  FC-收款联系人
					Map<Integer,String> cvTypeMap = new HashMap<Integer, String>();
					cvTypeMap.put(2020, "CT");  //BD联系人
					cvTypeMap.put(2021, "CP"); //合作决策人
					cvTypeMap.put(2022, "JC");  //职位联系人
					cvTypeMap.put(2023, "FC"); //收款联系人
					Integer  cvTypeCode = Integer.valueOf(cv.getCvType());
					if(cvTypeMap.containsKey(cvTypeCode)){
						//检查是否存在 同类型的客户联系人.
						//int count = customerContacterService.checkCustomerRoleCount(custId.toString(), cvTypeMap.get(cvTypeCode));
						//if(count<1 && count != -1){
							CustomerContacter  contacter = new CustomerContacter();
							contacter.setCreateDt(new Date());
							contacter.setCreator(cv.getCreator());
							contacter.setCvId(cv.getId());
							contacter.setRole(cvTypeMap.get(cvTypeCode));
							contacter.setCustId(custId);
							contacter.setComment("系统自动添加");
							//customerContacterService.save(contacter); //客户联系人
							customerContacterService.saveOrUpdate(contacter);
						//}
					}
				}
    		}
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	public void cvjoincompany(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		String ids = request.getParameter("cvIds");
		String companyId = request.getParameter("companyId");
		String deptId = request.getParameter("deptId");
		String titleId = request.getParameter("titleId");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
			 com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			 com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
			for (int i = 0; i < idarray.length; i++)
			{
				CompanyCv companyCv=new CompanyCv();
				companyCv.setCreator(onlineUser.getUsername());
				companyCv.setCreateDt(new Date());
				companyCv.setCompanyId(StringHelper.parseInteger(companyId, 0));
				companyCv.setDeptId(StringHelper.parseInteger(deptId, 0));
				companyCv.setTitleId(StringHelper.parseInteger(titleId, 0));
				
				java.lang.Integer id = new java.lang.Integer((String)idarray[i]);
				companyCv.setCvId(id);
				companyCvService.save(companyCv);
				
			}
			//自动并设置cc项目目标公司人选
			searchProjectCvService.addProjectCvByCompanyCv(StringHelper.parseInteger(companyId, 0));
			
			result.put("success", true);
			result.put("msg", "加入成功");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	/**
	 * extGrid删除
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
			for (int i = 0; i < idarray.length; i++)
			{
				java.lang.Integer id = new java.lang.Integer((String)idarray[i]);
				companyCvService.removeById(id);
			}
			result.put("success", true);
			result.put("msg", "删除成功");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	
}
